package com.chinatsp.aspect;


import com.chinatsp.entity.AuthInfo;
import com.chinatsp.entity.ResponseUtil;
import com.chinatsp.exception.BusinessException;
import com.chinatsp.util.StringUtils;
import com.chinatsp.util.SystemConstants;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;

/**
 * @ClassName: SpringBoot AOP
 * @Description: 公共组件, 验证拦截器
 * Created by chenzhengdong on 2017/3/29.
 */
@Aspect
@Component
public class HttpAspect {

    private final static Logger logger = LoggerFactory.getLogger(HttpAspect.class);

    ThreadLocal<Long> startTime = new ThreadLocal<>();

    @Pointcut("execution(public * com.chinatsp.controller..*(..))")
    public void log() {
    }

    @Before("log()")
    public boolean doBefore(JoinPoint joinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        //url
        logger.info("URL={}", request.getRequestURL());

        //method
        logger.info("METHOD={}", request.getMethod());

        //ip
        logger.info("IP={}", request.getRemoteAddr());

        //类方法
        logger.info("CLASS_METHOD={}", joinPoint.getSignature().getDeclaringTypeName() + "." +
                joinPoint.getSignature().getName());

        //参数
        try {
            logger.info("API.ACCESS={}", StringUtils.getQueryString(request));
            logger.info("COOKIE={}", request.getCookies());

        } catch (UnsupportedEncodingException e) {
            throw new BusinessException("9998", "解析HttpRequest参数失败");
        }

        // 从COOKIE中获取鉴权信息
        AuthInfo authInfo = StringUtils.getAccessToken(request);

        // 判断COOKIE中鉴权信息是否为空
        if (StringUtils.isEmpty(authInfo.getCustomer_key())
                || StringUtils.isEmpty(authInfo.getAccess_token())) {
            ResponseUtil.error(SystemConstants.Permissions_TokenLoss_CODE, SystemConstants
                    .Permissions_TokenLoss_DESC);
            return false;
        }
        return true;

    }

    /*@After("log()")
    public void doAfter() {
        logger.info("222222222222");
    }*/

    @Around("log()")
    public Object watchPerformance(ProceedingJoinPoint joinPoint) throws Throwable {
        Signature signature = joinPoint.getSignature();
        logger.debug("=================start {}=====================", signature.getName());

        StopWatch stopWatch = new StopWatch("controller");
        try {
            if (stopWatch.isRunning()) {
                stopWatch.stop();
            }

            stopWatch.start(signature.toString());
        } catch (IllegalStateException e) {
            logger.error("watch start error:", e);
        }

        Object proceed = joinPoint.proceed();

        try {
            if (stopWatch.isRunning()) {
                stopWatch.stop();
                logger.debug(stopWatch.prettyPrint() + "\n================= end " +
                        "{}=====================", signature.getName());
            }
        } catch (IllegalStateException e) {
            logger.error("watch end error:", e);
        }

        return proceed;
    }

    @AfterReturning(returning = "object", pointcut = "log()")
    public void doAfterReturning(Object object) {
        // 处理完请求，返回内容
        logger.info("RESPONSE={}", object.toString());
    }


}
